#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
//对于下标访问运算符进行重载
class CharArray{
public:
    CharArray(int size)
    :_pstr(new char[size + 1]())
     ,_size(size)
    {
        cout << "CharArray(int)" << endl;
    }

    ~CharArray(){
        if(_pstr){
            delete [] _pstr;
            _pstr = nullptr;
        }
    }

    //成员函数形式
    char & operator[](size_t index){
        if(index >= _size){
            //校验索引是否有效，如果无效则直接返回一个\0
            static char nullchar = '\0';
            return nullchar;
        }
        return _pstr[index];
    }

    int size() const {
        return _size;
    }

private:
    char * _pstr;
    int _size;
};
void test(){
    CharArray ch(10);
    ch[0] = 'H';
    ch[1] = 'e';
    ch[2] = 'l';
    ch[3] = 'l';
    ch[4] = 'o';
    cout << ch[3] << endl;
    for(int i = 0; i < ch.size(); ++i){
        cout << ch[i] << endl;
    }
}

void test2(){
    vector<int> numbers(10, 20);
    cout << numbers[0] << endl;
    numbers[2] = 30;
}

int main()
{
    test();
    return 0;
}

